<template>
  <div class="my-position-container">
    <el-card class="position-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Briefcase /></el-icon>
            <span class="header-title">我的岗位</span>
          </div>
          <div class="header-right">
            <el-tag type="info" size="large">
              共 {{ total }} 个岗位
            </el-tag>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="tableData.length === 0" class="empty-container">
        <el-empty 
          description="暂无岗位信息" 
          :image-size="120"
        >
          <template #description>
            <p>您还没有申请任何岗位</p>
          </template>
        </el-empty>
      </div>

      <div v-else class="position-grid">
        <el-card 
          v-for="position in tableData" 
          :key="position.id"
          class="position-item"
          shadow="hover"
        >
          <div class="position-header">
            <div class="position-title">
              <el-icon class="title-icon"><OfficeBuilding /></el-icon>
              <h3>{{ position.positionName }}</h3>
            </div>
          </div>

          <div class="position-content">
            <div class="info-row">
              <div class="info-item">
                <label class="info-label">工作内容</label>
                <div class="info-value description">{{ position.description }}</div>
              </div>
            </div>

            <div class="info-grid">
              <div class="info-item">
                <label class="info-label">
                  <el-icon><Location /></el-icon>
                  工作地点
                </label>
                <div class="info-value">{{ position.location }}</div>
              </div>

              <div class="info-item">
                <label class="info-label">
                  <el-icon><Money /></el-icon>
                  薪资标准
                </label>
                <div class="info-value salary">{{ position.salary }} 元/小时</div>
              </div>

              <div class="info-item">
                <label class="info-label">
                  <el-icon><Clock /></el-icon>
                  工作时间
                </label>
                <div class="info-value">{{ position.workTime }}</div>
              </div>

              <div class="info-item">
                <label class="info-label">
                  <el-icon><Timer /></el-icon>
                  已完成工时
                </label>
                <div class="info-value hours">{{ position.totalHours || 0 }} 小时</div>
              </div>
            </div>
          </div>

          <div class="position-footer">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewDetails(position)"
              :icon="View"
            >
              查看详情
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              @click="showWorkTimeDialog(position)"
              :icon="Plus"
            >
              申请工时
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div v-if="total > pageSize" class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="岗位详情"
      width="600px"
      :before-close="handleDetailDialogClose"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="岗位名称">{{ currentDetail.positionName }}</el-descriptions-item>
          <el-descriptions-item label="工作地点">{{ currentDetail.location }}</el-descriptions-item>
          <el-descriptions-item label="薪资标准">{{ currentDetail.salary }}元/小时</el-descriptions-item>
          <el-descriptions-item label="工作时间">{{ currentDetail.workTime }}</el-descriptions-item>
          <el-descriptions-item label="已完成工时">{{ currentDetail.totalHours || 0 }}小时</el-descriptions-item>
          <el-descriptions-item label="工作内容" :span="2">{{ currentDetail.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 工时申请对话框 -->
    <el-dialog
      v-model="workTimeDialogVisible"
      title="工时记录申请"
      width="600px"
      :before-close="handleWorkTimeDialogClose"
    >
      <el-form 
        :model="workTimeForm" 
        :rules="workTimeRules" 
        ref="workTimeFormRef" 
        label-width="100px"
      >
        <el-form-item label="岗位名称">
          <el-input :value="currentPosition?.positionName" disabled />
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker 
            v-model="workTimeForm.startTime" 
            type="datetime" 
            placeholder="选择开始时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="workTimeForm.endTime" 
            type="datetime" 
            placeholder="选择结束时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="工作描述" prop="description">
          <el-input 
            v-model="workTimeForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入工作内容" 
          />
        </el-form-item>
        
        <el-form-item label="证明图片" prop="file">
          <div class="upload-container">
            <el-upload
              class="image-uploader"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              accept=".jpg,.jpeg"
            >
              <div v-if="!imageUrl" class="upload-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击上传图片</div>
                <div class="upload-tip">仅支持jpg格式</div>
              </div>
              <img v-else :src="imageUrl" class="uploaded-image" />
            </el-upload>
            <div v-if="imageUrl" class="image-actions">
              <el-button type="danger" size="small" @click="removeImage">删除图片</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="workTimeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitWorkTime" :loading="submitting">
          提交申请
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Briefcase, 
  OfficeBuilding, 
  Location, 
  Money, 
  Clock, 
  Timer, 
  View, 
  Plus 
} from '@element-plus/icons-vue';
import axios from 'axios';

const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(6);
const loading = ref(false);
const detailDialogVisible = ref(false);
const currentDetail = ref(null);
const workTimeDialogVisible = ref(false);
const currentPosition = ref(null);
const submitting = ref(false);
const imageUrl = ref('');
const workTimeFormRef = ref(null);

const workTimeForm = reactive({
  positionName: '',
  positionDescription: '',
  positionLocation: '',
  positionWorkTime: '',
  positionSalary: '',
  startTime: '',
  endTime: '',
  description: '',
  file: null
});

const workTimeRules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入工作内容', trigger: 'blur' }],
  file: [{ required: true, message: '请上传jpg图片', trigger: 'change' }]
};

const fetchData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }
    const res = await axios.get('/api/student/my-position', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      },
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    if (res.data && res.data.code === 0) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg || '加载失败');
    }
  } catch (e) {
    ElMessage.error('请求失败: ' + e.message);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (val) => {
  pageNum.value = val;
  fetchData();
};

const viewDetails = (position) => {
  currentDetail.value = position;
  detailDialogVisible.value = true;
};

const showWorkTimeDialog = (position) => {
  currentPosition.value = position;
  workTimeForm.positionName = position.positionName;
  workTimeForm.positionDescription = position.description;
  workTimeForm.positionLocation = position.location;
  workTimeForm.positionWorkTime = position.workTime;
  workTimeForm.positionSalary = position.salary;
  workTimeForm.startTime = '';
  workTimeForm.endTime = '';
  workTimeForm.description = '';
  workTimeForm.file = null;
  imageUrl.value = '';
  workTimeDialogVisible.value = true;
};

const handleDetailDialogClose = () => {
  detailDialogVisible.value = false;
  currentDetail.value = null;
};

const handleWorkTimeDialogClose = () => {
  workTimeDialogVisible.value = false;
  currentPosition.value = null;
  workTimeForm.positionName = '';
  workTimeForm.positionDescription = '';
  workTimeForm.positionLocation = '';
  workTimeForm.positionWorkTime = '';
  workTimeForm.positionSalary = '';
  workTimeForm.startTime = '';
  workTimeForm.endTime = '';
  workTimeForm.description = '';
  workTimeForm.file = null;
  imageUrl.value = '';
  workTimeFormRef.value?.clearValidate();
};

const handleFileChange = (file) => {
  workTimeForm.file = file.raw;
  imageUrl.value = URL.createObjectURL(file.raw);
};

const beforeUpload = (file) => {
  const isJpg = file.type === 'image/jpeg';
  if (!isJpg) {
    ElMessage.error('只能上传jpg格式图片');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
    return false;
  }
  return true;
};

const removeImage = () => {
  workTimeForm.file = null;
  imageUrl.value = '';
  workTimeFormRef.value?.clearValidate('file');
};

const submitWorkTime = async () => {
  if (!workTimeFormRef.value) return;
  
  try {
    await workTimeFormRef.value.validate();
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确');
    return;
  }

  // 验证岗位关键信息
  if (!workTimeForm.positionName || !workTimeForm.positionDescription || !workTimeForm.positionLocation || !workTimeForm.positionWorkTime || !workTimeForm.positionSalary) {
    ElMessage.error('岗位信息不完整');
    return;
  }

  submitting.value = true;
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('请先登录');
      return;
    }
    
    const formData = new FormData();
    formData.append('positionName', workTimeForm.positionName);
    formData.append('positionDescription', workTimeForm.positionDescription);
    formData.append('positionLocation', workTimeForm.positionLocation);
    formData.append('positionWorkTime', workTimeForm.positionWorkTime);
    formData.append('positionSalary', workTimeForm.positionSalary);
    formData.append('startTime', workTimeForm.startTime);
    formData.append('endTime', workTimeForm.endTime);
    formData.append('description', workTimeForm.description);
    formData.append('file', workTimeForm.file);
    
    const res = await axios.post('/api/student/work-time-record', formData, {
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    });
    
    if (res.data.code === 0) {
      ElMessage.success('工时申请提交成功');
      workTimeDialogVisible.value = false;
      // 重新加载数据
      await fetchData();
      // 重置表单
      workTimeForm.positionName = '';
      workTimeForm.positionDescription = '';
      workTimeForm.positionLocation = '';
      workTimeForm.positionWorkTime = '';
      workTimeForm.positionSalary = '';
      workTimeForm.startTime = '';
      workTimeForm.endTime = '';
      workTimeForm.description = '';
      workTimeForm.file = null;
      imageUrl.value = '';
      workTimeFormRef.value.resetFields();
    } else {
      ElMessage.error(res.data.msg || '提交失败');
    }
  } catch (e) {
    console.error('提交失败:', e);
    if (e.response && e.response.data) {
      ElMessage.error('提交失败: ' + (e.response.data.message || e.response.data.error || '未知错误'));
    } else {
      ElMessage.error('提交失败: ' + e.message);
    }
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.my-position-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.position-card {
  max-width: 1400px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  gap: 12px;
}

.loading-container {
  padding: 40px 20px;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.position-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
  padding: 20px 0;
}

.position-item {
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
}

.position-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.position-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.title-icon {
  font-size: 20px;
  color: #409eff;
}

.position-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.position-content {
  margin-bottom: 20px;
}

.info-row {
  margin-bottom: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.info-label .el-icon {
  font-size: 14px;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  line-height: 1.4;
}

.info-value.description {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.info-value.salary {
  color: #f56c6c;
  font-weight: 600;
}

.info-value.hours {
  color: #67c23a;
  font-weight: 600;
}

.position-footer {
  display: flex;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.pagination-wrapper {
  margin-top: 32px;
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.detail-content {
  padding: 20px 0;
}

/* 工时申请弹窗样式 */
.upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.image-uploader {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;
  text-align: center;
}

.upload-icon {
  font-size: 36px;
  color: #c0c4cc;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
}

.uploaded-image {
  width: 150px;
  height: 120px;
  object-fit: cover;
  border-radius: 6px;
}

.image-actions {
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-position-container {
    padding: 16px;
  }
  
  .position-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .position-footer {
    flex-direction: column;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .header-right {
    margin-top: 8px;
  }
}

@media (max-width: 480px) {
  .position-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 